#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <iostream>
#include <string.h>
#include <QByteArray>
using namespace std;

double ACC_STEP=0.25;
double SLOWACC_STEP=0.1;
double angle_step=0.1;


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);
    last_ang=0;
    connect(tcpSocket,&QTcpSocket::connected,[=](){
        ui->label->setText(tr("connect phone successfully!"));
    });

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
        QByteArray buf = tcpSocket->readAll();
        char *temp = buf.data();
        server_recv(temp);
    });

    angle_mode=false;
    start=false;
    showLast=false;
    showTimes=0;

    song = new QMediaPlayer;
   // song->setMedia(QUrl::fromLocalFile("d:\\music.mp3"));
   // song->play();

    points[0]=QPointF(-CAR_W,0);
    points[1]=QPointF(0,-CAR_H);
    points[2]=QPointF(CAR_W,0);
    points[3]=QPointF(CAR_W,CAR_H);
    points[4]=QPointF(-CAR_W,CAR_H);

    initParam();

    ui->label3->setText(tr("AngleStep(5/6):")+QString::number(angle_step)+tr(" | Acc(7-0):")+QString::number(ACC_STEP));
    ui->label2->setText(tr("MaxSpeed(1/2):")+QString::number(car.max_speed,'g',2)+tr(" | F_Acc(3/4):")+QString::number(car.f));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::server_recv(char recvBuf[])
{
    double ang=0;
    double a=0;
    sscanf(recvBuf,"%lf %lf",&ang,&a);

   // cout <<ang<<" "<<a<<endl;
    if(ang==-2)
        car.setAcc(ACC_STEP*a);
    else if(a==-2)
    {
        car.setAngleSpeed(ang*angle_step);
    }
    else
    {
        car.setAcc(ACC_STEP*a);
        car.setAngleSpeed(ang*angle_step);
    }

    ui->label3->setText(tr("AngleStep:")+QString::number(ang*angle_step)+tr(" | Acc:")+QString::number(ACC_STEP*a));
}

void MainWindow::initParam()
{
    FILE *p=fopen("set.ini","r");
    if(p==NULL)
    {
        ui->label4->setText(tr("set.ini !?"));
        return ;
    }
    char str[200];
    char songName[200];
    char ip[50];
    while(!feof(p))
    {
        fscanf(p,"%s",str);
        if(strcmp(str,"background")==0)
            fscanf(p,"%s",backImage);
        else if(strcmp(str,"map")==0)
            fscanf(p,"%s",mapImage);
        else if(strcmp(str,"acc_step")==0)
            fscanf(p,"%lf",&ACC_STEP);
        else if(strcmp(str,"slowacc_step")==0)
            fscanf(p,"%lf",&SLOWACC_STEP);
        else if(strcmp(str,"angle_step")==0)
            fscanf(p,"%lf",&angle_step);
        else if(strcmp(str,"max_speed")==0)
            fscanf(p,"%lf",&max_speed);
        else if(strcmp(str,"facc")==0)
            fscanf(p,"%lf",&facc);
        else if(strcmp(str,"song")==0)
            fscanf(p,"%s",songName);
        else if(strcmp(str,"phoneIP")==0)
        {
            fscanf(p,"%s",ip);
            tcpSocket->connectToHost(QHostAddress(tr(ip)),8333);
        }
    }

    song->setMedia(QUrl::fromLocalFile(songName));
    car.init(facc,max_speed);
    readMap();
    fclose(p);
}


void MainWindow::readMap()
{
    back=QImage(backImage); //建立QImage类对象image
    QImage img(mapImage);
    int w=img.width();
    int h=img.height();

    car.initMap(w,h);
    for(int i=0;i<w;i++)
    {
        for(int j=0;j<h;j++)
        {
            QRgb temp=img.pixel(i,j);
            int r=qRed(temp);
            int g=qGreen(temp);
            int b=qBlue(temp);
            if(r>200&&g>200&&b<30||r>200&&g<30&&b<30)
                car.map[i][j]=1;
            else if(r<30&&g>200&&b<30)
                car.map[i][j]=2;
            else
                car.map[i][j]=0;
        }
    }

    Iwidth=img.width();
    Iheight=img.height();

    this->resize(Iwidth,Iheight);
}

void MainWindow::paintEvent(QPaintEvent *) {

    QRectF target(0, 0, Iwidth, Iheight);
    QPainter painter1(this);
    painter1.drawImage(target, back, target);

    QPainter painter(this); // this 是 的指针
    painter.setPen(Qt::blue);
    painter.setBrush(Qt::green);
    painter.translate(car.x, car.y);
    painter.rotate(car.angle/PI*180);
    painter.drawPolygon(points, 5);

    if(showLast&&showTimes<savePath.size())
    {
        QPainter painter2(this); // this 是 的指针
        painter2.setPen(Qt::blue);
        painter2.setBrush(Qt::lightGray);
        painter2.translate(savePath[showTimes].x, savePath[showTimes].y);
        painter2.rotate(savePath[showTimes].angle/PI*180);
        painter2.drawPolygon(points, 5);
    }
}



void MainWindow::keyPressEvent(QKeyEvent *ev)
{
    if(ev->key()==Qt::Key_F&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(-1*angle_step);
    }
    else if(ev->key()==Qt::Key_T&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(-0.05);
    }
    else if(ev->key()==Qt::Key_K&&!ev->isAutoRepeat())
    {
        car.setAcc(ACC_STEP);
    }
    else if(ev->key()==Qt::Key_J&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(angle_step);
    }
    else if(ev->key()==Qt::Key_U&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(0.05);
    }
    else if(ev->key()==Qt::Key_D&&!ev->isAutoRepeat())
    {
        car.setAcc(-1*SLOWACC_STEP);
    }
    //control
    else if(ev->key()==Qt::Key_1)//maxspeed
    {
        car.max_speed+=0.1;
        ui->label2->setText(tr("MaxSpeed:")+QString::number(car.max_speed,'g',2)+tr(" | F_Acc:")+QString::number(car.f));
    }
    else if(ev->key()==Qt::Key_2)
    {
        car.max_speed=MAX(0,car.max_speed-0.1);
        ui->label2->setText(tr("MaxSpeed:")+QString::number(car.max_speed,'g',2)+tr(" | F_Acc:")+QString::number(car.f));
    }
    else if(ev->key()==Qt::Key_3)//f_acc
    {
        car.f+=0.01;
        ui->label2->setText(tr("MaxSpeed:")+QString::number(car.max_speed,'g',2)+tr(" | F_Acc:")+QString::number(car.f));
    }
    else if(ev->key()==Qt::Key_4)
    {
        car.f=MAX(0,car.f-0.01);
        ui->label2->setText(tr("MaxSpeed:")+QString::number(car.max_speed,'g',2)+tr(" | F_Acc:")+QString::number(car.f));
    }
    else if(ev->key()==Qt::Key_5)//angle step
    {
        angle_step+=0.01;
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc:")+QString::number(ACC_STEP));
    }
    else if(ev->key()==Qt::Key_6)//angle step
    {
        angle_step=MAX(0,angle_step-0.01);
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc:")+QString::number(ACC_STEP));
    }
    else if(ev->key()==Qt::Key_7)//acc
    {
        ACC_STEP+=0.02;
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc:")+QString::number(ACC_STEP));
    }
    else if(ev->key()==Qt::Key_8)//
    {
        ACC_STEP=MAX(0,ACC_STEP-0.02);
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc:")+QString::number(ACC_STEP));
    }
    else if(ev->key()==Qt::Key_9)//acc
    {
        SLOWACC_STEP+=0.01;
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | SlowAcc:")+QString::number(SLOWACC_STEP));
    }
    else if(ev->key()==Qt::Key_0)//
    {
        SLOWACC_STEP=MAX(0,SLOWACC_STEP-0.01);
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | SlowAcc:")+QString::number(SLOWACC_STEP));
    }

    else if(ev->key()==Qt::Key_G)
    {
        longAcc=true;
        car.setAcc(ACC_STEP);
        ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc(Long):")+QString::number(ACC_STEP));
    }
    else if(ev->key()==Qt::Key_H&&!ev->isAutoRepeat())
    {
        longAcc=false;
    }
    else if(ev->key()==Qt::Key_M&&!ev->isAutoRepeat())
    {
        createMap.init();
        createMap.show();
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *ev)
{
    if(ev->key()==Qt::Key_F&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(0);
    }
    else if(ev->key()==Qt::Key_T&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(0);
    }
    else if(ev->key()==Qt::Key_K&&!ev->isAutoRepeat())
    {
        car.setAcc(0);
    }
    else if(ev->key()==Qt::Key_J&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(0);
    }
    else if(ev->key()==Qt::Key_U&&!ev->isAutoRepeat())
    {
        car.setAngleSpeed(0);
    }
    else if(ev->key()==Qt::Key_D&&!ev->isAutoRepeat())
    {
        if(longAcc)
        {
            car.setAcc(ACC_STEP);
            ui->label3->setText(tr("AngleStep:")+QString::number(angle_step)+tr(" | Acc(Long):")+QString::number(ACC_STEP));
        }
        else
            car.setAcc(0);
    }
}

void MainWindow::drawCar()
{
    car.update();
    double t=sqrt(car.vx*car.vx+car.vy*car.vy);
    ui->label->setText(tr("Speed: ")+QString::number(t,'g',2)+tr(" Acc: ")+QString::number(car.acc,'g',2));
    this->update();
    if(car.end!=0)
    {
        ui->label4->setText(tr("Complete!!!"));
        m_timer->stop();
        ui->car->setText("Start");
        start=false;
        song->stop();
        return ;
    }
    showTimes++;

    if(song->state()==0)//StoppedState
        song->play();
}

void MainWindow::start_show()
{
    sec++;
    if(sec<=3)
        ui->label4->setText(QString::number(sec)+tr("S"));
    else if(sec==4)
    {
        car.init(car.f,car.max_speed);
        car.max_x=Iwidth;
        car.max_y=Iheight;

        longAcc=false;
        showTimes=0;
        ui->label4->setText(tr("Go!!"));
        m_timer = new QTimer(this);
        //设置定时器是否为单次触发。默认为 false 多次触发
        m_timer->setSingleShot(false);
        //启动或重启定时器, 并设置定时器时间：毫秒
        m_timer->start(30/NUM);
        //定时器触发信号槽
        connect(m_timer, SIGNAL(timeout()), this, SLOT(drawCar()));
        ui->car->setText("Close");
    }
    else{
        show_timer->stop();
        ui->label4->setText(tr(""));
    }
}

void MainWindow::on_car_clicked()
{
    if(!start)
    {
        show_timer = new QTimer(this);
        //设置定时器是否为单次触发。默认为 false 多次触发
        show_timer->setSingleShot(false);
        //启动或重启定时器, 并设置定时器时间：毫秒
        show_timer->start(1000);
        sec=0;
        connect(show_timer, SIGNAL(timeout()), this, SLOT(start_show()));
        start=true;
        song->play();
    }
    else
    {
        m_timer->stop();
        ui->car->setText("Start");
        start=false;
    }
}

void MainWindow::on_car_3_clicked()
{
    if(showLast)
        showLast=false;
    else
        showLast=true;

    if(!showLast)
        ui->car_3->setText(tr("Last"));
    else
        ui->car_3->setText(tr("No"));
}

void MainWindow::on_car_4_clicked()
{
    savePath.clear();
    for(int i=0;i<car.path.size();i++)
    {
        IPoint t=car.path[i];
        savePath.push_back(t);
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        if(showTimes==0)
        {
            car.initx=event->pos().x();
            car.inity=event->pos().y();

            car.x=event->pos().x();
            car.y=event->pos().y();

            this->update();
        }
    }
    // 如果是鼠标右键按下
    else if(event->button() == Qt::RightButton)
    {
        if(showTimes==0)
        {
            car.initAngle+=0.05;
            car.angle=car.initAngle;

            this->update();
        }
    }
}
